public class ReadPhoneUtil {
	/*
	  此类集合读取设备各种信息功能
	  使用此类请保证相关权限已被允许
	  建议在读取数据量多时开启线程，如联系人，信息，通话记录等
	  类内不提供线程，不提供权限请求
	*/
   
	//获取设备屏幕信息，返回String:dp px dpi
	private static String get_phone_pxdpdpi(){
        WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
        int width = wm.getDefaultDisplay().getWidth();
        int hight=wm.getDefaultDisplay().getHeight();
        String s1="px屏幕宽"+width+"高"+hight;
        String s2="dp屏幕宽"+px2dip(this,width)+"高"+px2dip(this,hight);
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        String s3="屏幕dpi"+ metric.densityDpi;
		return s1+"\n"+s2+"\n"+s3;
	}


	//获取设备信息，返回String:厂商,型号,系统
    private static String get_phone_xinghao(){
       try{
           SimpleDateFormat formatter=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
           Date curDate=new Date(System.currentTimeMillis());
           String s0="获取时间 : "+formatter.format(curDate)+"\n\n";
           String s1="手机厂商 : "+android.os.Build.BRAND+"\n\n";
           String s2="手机型号 : "+android.os.Build.MODEL+"\n\n";
           String s3="系统版本 : "+android.os.Build.VERSION.RELEASE;
           return s0+s1+s2+s3;
       }catch (Exception e){
           return e.toString();
       }
    }
	
	//获取电池信息，返回String:电量，用什么充电
    private static String get_phone_dianchi(){
        String s1="",s2="";
        try{
            IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
            Intent batteryStatus = registerReceiver(null, ifilter);
            int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
            boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL;
            if(isCharging){
                int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
                boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
                boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
                if(usbCharge){
                    s1="充电信息 : 充电中（电脑USB）";
                }else {
                    s1="充电信息 : 充电中（电源线）";
                }
            }else {
                s1="充电信息 : 未充电";
            }
            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            NumberFormat nnn=NumberFormat.getInstance();
            nnn.setMaximumFractionDigits(0);
            String ssjjj=nnn.format((float)level/(float)scale*100);
            s2="剩余电量 : "+ssjjj+"%";
            return s1+"\n"+s2;
        }catch (Exception e){
            return e.toString();
        }
    }
	
	//获取网络信息，返回String:网络类型，流量或wifi
    private static String get_phone_intenet(){
        try {
            ConnectivityManager cm;
            cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean isWifitrue = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED ? true : false;
            if(isWifitrue){
                return "网络类型 : WIFI";
            }else {
                return "网络类型 : 流量";
            }
        }catch (Exception e){
            return e.toString();
        }
    }
	
	//获取存储信息，返回String:内存+外存
    private static String get_phone_neicun(){
        String s1="",s2="";
        try{
            File path = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(path.getPath());
            long blockSize = stat.getBlockSize();
            long totalBlocks = stat.getBlockCount();
            long availableBlocks = stat.getAvailableBlocks();
            String zong= Formatter.formatFileSize(this, blockSize * totalBlocks).replaceAll(" ","");
            String keyong=Formatter.formatFileSize(this, blockSize * availableBlocks).replaceAll(" ","");
            s1="存储空间 : 总共"+zong+",可用"+keyong+"\n\n";
            /////////////////////////////////////////////////////////
            ActivityManager mActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
            //获得MemoryInfo对象
            ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo() ;
            //获得系统可用内存，保存在MemoryInfo对象上
            mActivityManager.getMemoryInfo(memoryInfo) ;
            long memSize = memoryInfo.totalMem ;
            long memSize2 = memoryInfo.availMem ;
            //字符类型转换
            String availMemStr = Formatter.formatFileSize(this, memSize).replaceAll(" ","");
            String availMemStr2 =Formatter.formatFileSize(this, memSize2).replaceAll(" ","");
            s2="系统内存 : 总共"+availMemStr+",可用"+availMemStr2;
            return s1+s2;
        }catch (Exception e){
            return e.toString();
        }
    }
	
	//获取设备亮度，返回String:亮度
    private static String get_phone_liangdu(){
        try{
            WindowManager wm = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
            int width = wm.getDefaultDisplay().getWidth();
            int hight=wm.getDefaultDisplay().getHeight();
            int liangdu = Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
            NumberFormat nnn=NumberFormat.getInstance();
            nnn.setMaximumFractionDigits(0);
            String ssjjj=nnn.format((float)liangdu/(float)255*100);
            return "屏幕亮度 : "+width+"*"+hight+",当前亮度"+ssjjj+"%";
        }catch (Exception e){
            return e.toString();
        }
    }
	
	//获取已安装APP，返回String:已安装APP
    private static String get_phone_app(){
        String s1="已装应用 : ";
        try{
            //获取全部应用：
            PackageManager packageManager = this.getPackageManager();
            List<PackageInfo> packageInfoList =packageManager.getInstalledPackages(0);
            //判断是否系统应用：
            List<PackageInfo> apps = new ArrayList<PackageInfo>();
            for (int i = 0; i < packageInfoList.size(); i++) {
                PackageInfo pak = (PackageInfo)packageInfoList.get(i);
                //判断是否为系统预装的应用
                if ((pak.applicationInfo.flags & pak.applicationInfo.FLAG_SYSTEM) <= 0) {
                    // 第三方应用
                    apps.add(pak);
                } else {
                    //系统应用
                }
            }
            for(int i = 0; i < apps.size(); i++){
                /**
                 * PackageInfo mPackageInfo;
                 获取包名： mPackageInfo.packageName
                 获取icon： mPackageInfo.getApplicationIcon(applicationInfo);
                 获取应用名： mPackageInfo.getApplicationLabel(applicationInfo);
                 获取使用权限：
                 mPackageInfo.getPackageInfo(packageName,PackageManager.GET_PERMISSIONS).requestedPermissions;
                 */
                PackageInfo pak = apps.get(i);
                s1+=pak.applicationInfo.loadLabel(getPackageManager()).toString()+"/";
            }
            return s1;
        }catch (Exception e){
            return e.toString();
        }
    }

	//获取联系人，返回String:联系人
    private static String get_xx_lxr(){
	    int PHONES_DISPLAY_NAME_INDEX = 0;//姓名
        int PHONES_NUMBER_INDEX = 1;//电话号码
        try{
            String all_people="";
            ContentResolver resolver = getContentResolver();
            Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);
            if (phoneCursor != null) {
                while (phoneCursor.moveToNext()) {
                    //得到手机号码
                    String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);
                    //当手机号码为空的或者为空字段 跳过当前循环
                    if (TextUtils.isEmpty(phoneNumber)) continue;
                    //得到联系人名称
                    String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);
                    //得到联系人ID
                    Long contactid = phoneCursor.getLong(PHONES_NUMBER_INDEX);
                    all_people+=contactName+":"+contactid+"\n";
                }
                phoneCursor.close();
                return all_people;
            }else {
                return "您禁止了读取联系人，请去手机设置中更改";
            }
        }catch (Exception e){
            return e.toString();
        }
    }
	
	//获取短信记录，返回String:短信内容
    private static String get_xx_sms(){
        try{
            final String SMS_URI_ALL = "content://sms/";
            final String SMS_URI_INBOX = "content://sms/inbox";
            final String SMS_URI_SEND = "content://sms/sent";
            final String SMS_URI_DRAFT = "content://sms/draft";
            final String SMS_URI_OUTBOX = "content://sms/outbox";
            final String SMS_URI_FAILED = "content://sms/failed";
            final String SMS_URI_QUEUED = "content://sms/queued";
            final StringBuilder smsBuilder = new StringBuilder();
            Uri uri = Uri.parse(SMS_URI_ALL);
            String[] projection = new String[]{"_id", "address", "person", "body", "date", "type"};
            Cursor cur =getContentResolver().query(uri, projection, null, null, "date desc");     
            if(cur!=null){
                if (cur.moveToFirst()) {
                    int index_Address = cur.getColumnIndex("address");
                    int index_Person = cur.getColumnIndex("person");
                    int index_Body = cur.getColumnIndex("body");
                    int index_Date = cur.getColumnIndex("date");
                    int index_Type = cur.getColumnIndex("type");
                    do {
                        String strAddress = cur.getString(index_Address);
                        int intPerson = cur.getInt(index_Person);
                        String strbody = cur.getString(index_Body);
                        long longDate = cur.getLong(index_Date);
                        int intType = cur.getInt(index_Type);
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
                        java.sql.Date d = new java.sql.Date(longDate);
                        String strDate = dateFormat.format(d);
                        String strType = "";
                        if (intType == 1) {
                            strType = "收到";
                        } else if (intType == 2) {
                            strType = "发给";
                        } else {
                            strType = "null";
                        }
                        smsBuilder.append(strDate + "");
                        smsBuilder.append(strType);
                        smsBuilder.append(strAddress + "的短信 : ");
                        smsBuilder.append(strbody + "\n");
                    } while (cur.moveToNext());
                    if (!cur.isClosed()) {
                        cur.close();
                        cur = null;
                    }
                } else {
                    smsBuilder.append("暂无更多");
                }
                return smsBuilder.toString();
            }else {
				return "权限被禁止";
            }
        }catch (Exception e){
            return e.toString();
        }
    }
	
	//获取通话记录，返回String:通话记录
    private static String get_xx_log(){
        try{
                String ccs = "";
                Cursor cursor = getContentResolver().query(CallLog.Calls.CONTENT_URI, new String[]{
                        CallLog.Calls.CACHED_NAME,  //姓名
                        CallLog.Calls.NUMBER,    //号码
                        CallLog.Calls.TYPE,  //呼入/呼出(2)/未接
                        CallLog.Calls.DATE,  //拨打时间
                        CallLog.Calls.DURATION   //通话时长
                }, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
                if(cursor!=null){
                    while (cursor.moveToNext()) {
                        String number = cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER));
                        String type;
                        switch (Integer.parseInt(cursor.getString(cursor.getColumnIndex(CallLog.Calls.TYPE)))) {
                            case CallLog.Calls.INCOMING_TYPE:
                                type = "呼入";
                                break;
                            case CallLog.Calls.OUTGOING_TYPE:
                                type = "呼出";
                                break;
                            case CallLog.Calls.MISSED_TYPE:
                                type = "未接";
                                break;
                            default:
                                type = "挂断";
                                break;
                        }
                        SimpleDateFormat sfd = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                        java.sql.Date date = new java.sql.Date(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.DATE))));
                        String time = sfd.format(date);
                        String name = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.CACHED_NAME));
                        String duration = cursor.getString(cursor.getColumnIndexOrThrow(CallLog.Calls.DURATION));
                        ccs = ccs + time + "-号码-" + number + "-" + type + "-时间:" + duration + "s\n";
                    }
                    return ccs;
                }else {
                    return "权限被禁止";
                }
        }catch (Exception e||SecurityException e){
            return "权限被禁止";
        }

    }

    private int dp2px(int x){
        final float a1=getResources().getDisplayMetrics().density;
        return  (int)(x*a1+0.5f);
    }

    public static int px2dip(Context context,float pxValue){
        final float scale = context.getResources ().getDisplayMetrics ().density;
        return (int) (pxValue / scale + 0.5f);
    }


   
}
